﻿#include "ElementsReader.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QJsonDocument>
#include <qicon.h>
#include "ElementtreeItem.h"
ElementsReader::ElementsReader() {}
/*
    DisplayRole = 0,// 显示的文字
    DecorationRole = 1,// 图标
    EditRole = 2, //
    ToolTipRole = 3, // 提示
    StatusTipRole = 4, // 状态栏信息
    WhatsThisRole = 5,
    // Metadata
    FontRole = 6, // 显示的文字字体
    TextAlignmentRole = 7, // 显示的文字对其方式
    BackgroundRole = 8,// 背景
*/
#include <Element/ElementBase.h>
static ElementBase::ElementUiBase* fromFile(const QString& fileName){

}
// auto* cur = (ElementGraphicsView *)ui->tabWidget->currentWidget();
// static ElementBase::ElementUiBase eui;
// eui.fromFile(":/config/elements/resistance.json");
// auto* item=new ElementBase(QSizeF(100.,20.),&eui);
// cur->scene()->addItem(item);//
// item->setPos(500,500);
// connect(item,&ElementBase::rotationChanged,this,[this, item](){
//     ui->statusbar->showMessageOnLeft(QString::number(item->rotation()));
// });

ElementTreeItem *ElementsReader::read(const QString &filePath) const
{
    QFile file(filePath);
    file.open(QIODeviceBase::ReadOnly);
    if(!file.isOpen()){
        return nullptr;
    }
    QByteArray json=file.readAll();
    QJsonDocument doc=QJsonDocument::fromJson(json);
    if(!doc.isObject()){
        return nullptr;
    }
    QJsonObject obj=doc.object();
    QStringList keys=obj.keys();
    ElementTreeItem *pFirstItem = new ElementTreeItem();
    pFirstItem->setValue(Qt::DisplayRole,"元件");
    for(int i=0;i<keys.length();++i){
        ElementTreeItem *itemi = new ElementTreeItem();
        itemi->setValue(Qt::DisplayRole,keys[i]);
        pFirstItem->appendChild(itemi);
        QJsonObject temObj = obj[keys[i]].toObject();
        itemi->setValue(Qt::DecorationRole,QIcon(temObj["icon"].toString()));
        QJsonArray temArray = temObj["elements"].toArray();
        for(int j=0;j<temArray.count();++j){
            ElementTreeItem *itemj = new ElementTreeItem();
            QJsonObject tem = temArray[j].toObject();
            itemj->setValue(Qt::DisplayRole,tem["title"].toVariant());
            itemj->setValue(Qt::DecorationRole,tem["image"].toVariant());
            ElementBase::ElementUiBase* eui=new ElementBase::ElementUiBase();
            eui->fromFile(tem["element"].toString());
            itemj->setValue(Qt::UserRole,ull(eui));
            itemi->appendChild(itemj);
        }
        itemi->setValue(Qt::BackgroundRole,temObj["background"].toVariant());
    }
    return pFirstItem;
}
